<template>
  <div id="app">
    <router-view />
    <theme-picker />
    <VersionUpdate
      :show.sync="versionUpdate.show"
      :isNew="versionUpdate.isNew"
      :versionNo="versionUpdate.versionNo"
      :updateContent="versionUpdate.updateContent"
    />
    <RechargeDetails :show.sync="TopUpNowPopFlage" />
  </div>
</template>

<script>
import ThemePicker from '@/components/ThemePicker'
import VersionUpdate from '@/components/VersionUpdate'
import RechargeDetails from '@/components/RechargeDetails'
import { dictGetDictList } from '@/api/public'

export default {
  name: 'App',
  components: { ThemePicker, VersionUpdate, RechargeDetails },
  data() {
    return {
      versionUpdate: {
        show: false,
        versionNo: '',
        isNew: false,
        updateContent: [],
      },
      TopUpNowPopFlage: false,
    }
  },
  metaInfo() {
    return {
      title: this.$store.state.settings.dynamicTitle && this.$store.state.settings.title,
      titleTemplate: (title) => {
        return title ? `${title} - ${process.env.VUE_APP_TITLE}` : process.env.VUE_APP_TITLE
      },
    }
  },
  async created() {
    /**初始化语言 */
    let lang = navigator.language || navigator.userLanguage //常规浏览器语言和IE浏览器
    let language = localStorage.getItem('language')
    if (language != undefined && language != null && language != '') {
      this.$store.dispatch('settings/changeLanguage', language)
    } else {
      this.$store.dispatch('settings/changeLanguage', lang.replace('-', '_'))
    }
    this.handleClick(this.$store.state.settings.language)
  },
  mounted() {
    setTimeout(() => {
      this.$Bus.$on('login-check-version', () => this.checkVersion(true, false))
      this.checkVersion(true)
    }, 2000)
    setInterval(() => {
      const sessionObj = JSON.parse(sessionStorage.getItem('sessionObj') || '{}')
      const { time } = sessionObj
      if (time) {
        // 判断登录时间是否小于 6个小时
        const flag = new Date().getTime() - time < 60 * 1000 * 60 * 6
        // 浏览器是否可见
        if (flag && document.visibilityState == 'visible') {
          this.checkVersion(false)
        }
      }
    }, 1000 * 60)
    // 获取全部字典信息
    this.getAllDict()
  },
  updated() {
    setTimeout(() => {
      this.isExpirationTime()
    }, 500)
  },
  methods: {
    getAllDict() {
      if (this.$store.state.user.token) {
        this.$store.dispatch('SET_USER_DICT')
      }
    },
    /**判断是否过期如果登录后显示过期*/
    isExpirationTime() {
      // oauth 页面不操作
      const { path } = this.$route
      const whiteList = ['/auth']
      if (whiteList.includes(path)) return
      // oauth 页面不操作

      if (this.$store.state.user.token) {
        if (!this.$store.state.user.expireFlag && this.$store.state.user.expireType == 0) {
          this.TopUpNowPopFlage = true
        }
      }
    },
    checkVersion(cache = false, noCheck = true) {
      const getLocalVersion = () => JSON.parse(localStorage.getItem('local-version') || '{}')

      // 以下路径不用检查更新
      const notIncludePaths = ['/login', '/platform/recommenSellerRegist']
      // console.log(`location.pathname ==>`, JSON.parse(JSON.stringify(location.pathname)))
      // 以下路径不用检查更新
      if (notIncludePaths.includes(location.pathname) && noCheck) {
        return
      }

      const { version_no: local_version_no } = getLocalVersion()
      // fetch('http://192.168.5.240:2333/assets/version.json')
      fetch(`/version.json?timestamp=${new Date().getTime()}`)
        .then((version) => version.json())
        .then((res) => {
          // 最新的数据
          const { version_no, update_content } = res

          // 如果本地没有提示过
          if (!local_version_no) {
            localStorage.setItem('local-version', JSON.stringify(res))
            // console.log(`当前版本为==> ${version_no} `)
            this.versionUpdate.versionNo = version_no
            this.versionUpdate.updateContent = update_content
            this.versionUpdate.show = true
            return
          }

          if (cache) {
            const { alerted } = getLocalVersion()
            // 设置已弹窗
            localStorage.setItem('local-version', JSON.stringify({ ...res, alerted: true }))
            // console.log(` getLocalVersion() ==>`, JSON.parse(JSON.stringify(getLocalVersion())))
            // console.log(`当前版本为==> ${version_no} `)
            if (!alerted) {
              this.versionUpdate.versionNo = version_no
              this.versionUpdate.updateContent = update_content
              this.versionUpdate.show = true
              return
            }

            return
          }

          // 版本不一致
          if (local_version_no != version_no) {
            // console.log(`当前版本为==> ${local_version_no} 最新版本为 ==> ${version_no}`)
            if (this.versionUpdate.show) return
            this.versionUpdate.versionNo = version_no
            this.versionUpdate.updateContent = update_content
            this.versionUpdate.isNew = true
            this.versionUpdate.show = true
            return
          } else {
            return console.log(`已经是最新版本!`)
          }
        })
    },
    handleClick(type, reload = false) {
      this.$store.dispatch('settings/changeLanguage', type)
      this.$i18n.locale = type
      localStorage.setItem('language', type)
      if (reload) this.$nextTick(() => window.location.reload())
    },
  },
}
</script>
<style scoped>
#app .theme-picker {
  display: none;
}
</style>
